var TUrl = ''
layui.config({
	base: '/plugins/layui/modules/' //假设这是你存放拓展模块的根目录
}).extend({ //设定模块别名
	myconfig: 'myconfig' //如果 config.js 是在根目录，也可以不用设定别名
});
layui.define([ 'laypage', 'table', 'form', 'laydate', 'myconfig' ], function(exports) {
	var table = layui.table,
		laypage = layui.laypage,
		laydate = layui.laydate,
		myconfig = layui.myconfig;
	TUrl = myconfig.getTUrl()
	// console.log(TUrl)

	var authentication = localStorage.getItem('xi-can-supplier-authentication')

	var http = {
		post : function(url, param, callback) {
			var load = layer.load(1, {
				shade : 0.3
			});
			$.ajax({
				type : "POST",
				url : TUrl + url,
				cache : false, // 禁用缓存
				data : param, // 传入组装的参数
				dataType : "json",
				headers:{
					authentication: authentication
				},
				success : function(data) {
					setTimeout(function() {
						layer.close(load);
					}, 200);
					if (data.code == 402) {
						location.href = "login.html";
					}else {
						callback(data);
					}
				},
				error : function() {
					layer.msg("请求异常");
					setTimeout(function() {
						layer.close(load);
					}, 200);
				},
				complete: function( xhr,data ){
					var authentication = xhr.getResponseHeader('authentication');
					if(authentication){
						localStorage.setItem("xi-can-supplier-authentication", authentication);
					}
				}
			});
		},
		postJSON: function (url, param, callback) {
            var load = layer.load(1, {
                shade: 0.3
            });
            $.ajax({
                type: "POST",
                url: TUrl + url,
                cache: false, // 禁用缓存
                data: param, // 传入组装的参数
                dataType: "json",
				headers:{
					"Content-Type":"application/json",
					authentication: authentication
				},
                success: function (data) {
                    setTimeout(function () {
                        layer.close(load);
                    }, 200);
                    if (data.code == 402) {
                        location.href = "login.html";
                    } else {
                        callback(data);
                    }
                },
                error: function () {
                    layer.msg("请求异常");
                    setTimeout(function () {
                        layer.close(load);
                    }, 200);
                },
				complete: function( xhr,data ){
					var authentication = xhr.getResponseHeader('authentication');
					if(authentication){
						localStorage.setItem("xi-can-supplier-authentication", authentication);
					}
				}
            });
        },
		upLoad: function (url, param, callback) { //上传文件
			var load = layer.load(1, {
				shade : 0.3
			});
			$.ajax({
				type: "POST",
				url: TUrl + url,
				cache: false, // 禁用缓存
				data: param, // 传入组装的参数
				contentType: false,
				processData: false,
				// async: false,
				headers:{
					authentication: authentication
				},
				success: function (data) {
					setTimeout(function() {
						layer.close(load);
					}, 200);
					if (data.code == 402) {
						location.href = "login.html";
					} else {
						callback(data);
					}
				},
				error: function () {
					layer.msg("请求异常");
					setTimeout(function () {
						layer.close(load);
					}, 200);
				},
				complete: function( xhr,data ){
					var authentication = xhr.getResponseHeader('authentication');
					if(authentication){
						localStorage.setItem("xi-can-supplier-authentication", authentication);
					}
				}
			});
		},
		get : function(url, param, callback) {
			$.ajax({
				type : "GET",
				url : TUrl + url + '?_='+(new Date().getTime()),
				cache : false, // 禁用缓存
				data : param, // 传入组装的参数
				dataType : "json",
				headers:{
					authentication: authentication
				},
				success : function(data) {
					if (data.code == 402) {
						location.href = "login.html";
					} else {
						callback(data);
					}
				},
				error : function() {
					layer.msg("请求异常");
					setTimeout(function () {
						layer.close(load);
					}, 200);
				},
				complete: function( xhr,data ){
					var authentication = xhr.getResponseHeader('authentication');
					if(authentication){
						localStorage.setItem("xi-can-supplier-authentication", authentication);
					}
				}
			});
		},
		table: function(options) {
			var tableIns = table.render({
				elem: options.elem,
				id: options.id,
				url: TUrl + options.url + '?_='+(new Date().getTime()),
				method: options.type || 'get',
				where: options.where || {},
				cellMinWidth: 100,
				height: options.height || 524,
				move : true,
				defaultToolbar : [],
				headers: {
					authentication: authentication
				},
				toolbar: options.toolbar || '',
				page : options.page || {
					layout : [ 'prev', 'page', 'next', 'count', 'limit', 'skip'],
					prev : '<em><</em>',
					next : '<em>></em>',
					limits: [10, 20, 50,100]
				},
				limit: options.limit || 10,
				cols: options.cols,
				done: options.done || function(res, curr, count){
	
				},
				response: {
					statusCode : 200 //重新规定成功的状态码为 200，table 组件默认为 0
				},
				parseData: function(res) {
					if (res.code == 402) {
						location.href = "login.html";
					}else if(res.code == 200){
						return {
							"code": res.code, //状态字段名称
							"msg": res.msg, //消息字段
							"count": res.data.count, //总数字段
							"data":res.data.list  //数据字段
						};

					}else{
						layer.msg(res.msg)
					}
				},
				request: {
					pageName : 'page', //页码的参数名称，默认：page,
					limitName : 'limit' //每页数据量的参数名，默认：limit
				}
			});
			return tableIns;
		},
		table1 : function(options) {
			var tableIns = table.render({
				elem : options.elem,
				id : options.id,
				cols : options.cols,
				move : true,
				toolbar : options.toolbar,
				defaultToolbar : [],
				page : options.page && {
					layout : [ 'prev', 'page', 'next', 'skip', 'count' ],
					prev : '<em><</em>',
					next : '<em>></em>'
				},
				limit: options.limit || 10,
				limits : options.limits || [ 10, 20, 30, 40 ],
				where : options.where || {},
				cellMinWidth : options.cellMinWidth||100,
				// size: 'sm' ,//小尺寸的表格
				// height : options.height || 523,
				data:options.data
			});
			return tableIns;
		},
		myOpen : function(options) {
			return layer.open({
				type : 1,
				title : options.title, //标题栏
				closeBtn : 1, //关闭按钮
				shade :options.shade, //遮罩 透明度
				area : options.area,
				skin : 'layui-layer-molv', //自定义样式
				id : options.id, //设定一个id，防止重复弹出
				btn : options.btn, //按钮
				scrollbar : false, //禁止浏览器滚动条
				btnAlign : 'r', //
				move : true, //禁止拖
				resize : false, //是否允许拉伸
				content : options.content,
				btn1: function(index, layero) {
					if (options.btn1) {
						options.btn1(index, layero);
					}
				},
				btn2: function(index, layero) {
					if (options.btn2) {
						options.btn2(index, layero);
						return false
					}else{
						layer.close(index);
					}
				},
				success: function(layero, index) {
					this.enterConfirm = function(event){
						// console.log(event.keyCode)
						if(event.keyCode === 13){
							$(".layui-layer-btn0").click();
							// console.log($(".layui-layer-btn0"))
							return false; //阻止系统默认回车事件
						}
					};
					$(document).on('keydown', this.enterConfirm); //监听键盘事件
			
					// 点击确定按钮回调事件
					$(".layui-layer-btn0").on("click",function() {
						// // console.log("peace and love");
					})
				},
				cancel : function(index, layero) {
					// console.log('cancel')
					layer.close(index);
				},
				end: function(){
					$(document).off('keydown', this.enterConfirm); //解除键盘事件
				}
			});

		},
		confirm : function(text, callback) {
			layer.confirm(text, {
				id : 'CE_deletepro',
				icon : 3,
				title : '温馨提示',
				skin : 'layui-layer-molv',
				resize : false,
				anim : Math.ceil(Math.random() * 6)
			}, callback || function() {});
		},
		msg : function(content) {
			layer.msg(content, {
				icon : 1,
				time : 2000 //2秒关闭（如果不配置，默认是3秒）
			}, function() {});
		},
		photos : function(contentId) {
			layer.open({
				type : 1,
				area : [ '450px', '450px' ],
				title : false, //不显示标题栏
				closeBtn : true,
				shade : 0.8,
				shadeClose : true, //默认fasle  是否点击遮罩关闭
				btnAlign : 'c',
				content : contentId
			});
		},
		page : function(pageId, total, pageSize, pageIndex, opentions) {
			laypage.render({
				elem : pageId,
				count : total, //总数
				limit : pageSize, //每页显示几条
				curr : pageIndex, //当前页
				layout : [ 'count', 'prev', 'page', 'next', 'limit', 'skip' ],
				jump : function(obj, first) {
					if (!first) {
						opentions(obj.curr);
					}
				}
			});
		},
		previewImage : function(imagefile, imgId) {
			for (var i = 0; i < imagefile.files.length; i++) {
				if (imagefile.files && imagefile.files[i]) {
					var reader = new FileReader();
					reader.onload = function(evt) {
						$("#" + imgId).attr("src", evt.target.result);
					};
					reader.readAsDataURL(imagefile.files[i]);
				}
			}
		},
		toBase64 : function(img) {
			img = TUrl + img;
			function getBase64Image(img, width, height) { //width、height调用时传入具体像素值，控制大小 ,不传则默认图像大小
				var canvas = document.createElement("canvas");
				canvas.width = width ? width : img.width;
				canvas.height = height ? height : img.height;

				var ctx = canvas.getContext("2d");
				ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
				var dataURL = canvas.toDataURL();
				return dataURL;
			}
			var image = new Image();
			image.crossOrigin = '';
			image.src = img;
			var deferred = $.Deferred();
			if (img) {
				image.onload = function() {
					deferred.resolve(getBase64Image(image)); //将base64传给done上传处理
				}
				return deferred.promise(); //问题要让onload完成后再return sessionStorage['imgTest']
			}
		},
		laydate : function(eId) {
			laydate.render({
				elem : '#' + eId
			});
		},
		getPid : function(name) {
			var search = document.location.href;
			var pattern = new RegExp("[?&]" + name + "\=([^&]+)", "g");
			var matcher = pattern.exec(search);
			var _pid = null;
			if (null != matcher) {
				try {
					_pid = decodeURIComponent(decodeURIComponent(matcher[1]));
				} catch (e) {
					try {
						_pid = decodeURIComponent(matcher[1]);
					} catch (e) {
						_pid = matcher[1];
					}
				}
			}
			return _pid;
		},
		IsMobilePhoneNumber: function(input) {
			var regex = /^1[345789]\d{9}$/;
			var regex1 = /^(5|6|8|9)\d{7}$/;
			if(input.match(regex)||input.match(regex1)) {
				return true;
			} else {
				return false;
			}
		},
		// 密码失焦验证
		verifPwd:function(password,password1,type){
			if(!password || !password1){
				return
			}
			if(password != '1234'){
			    if(!/^[0-9a-zA-Z]{6,20}$/.test(password)){
			        layer.msg('密码不规范')
			        return
			    }
			}
			if(password != password1){
			    layer.msg('密码不一致')
			    return
			}
		},
		// 获取后缀名
		getLaName:function(filevalue){
			var index = filevalue.lastIndexOf('.');
			return filevalue.substring(index+1);
		},
		// 文件类型限制
		isAssetType: function(sel) {
			return ['pdf','png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(sel) !== -1;
		},
		getUUID: function() {
		    function S4() {
		        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
		    }
		
		    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
		},
		//图片大小验证
		verificationPicFile: function(file,sizeTop) {
			var fileMaxSize = 1024*sizeTop;
			var fileSize = file.size; // 文件大小
			if(fileSize){
				fileSize = fileSize / 1024;
				if (fileSize > fileMaxSize) {
					layer.msg("文件大小不能大于"+(sizeTop==0.5?"500K":(sizeTop+"M"))+"！");
					return false;
				}else if (fileSize <= 0) {
					layer.msg("文件大小不能为0M！");
					return false;
				}else{
					return true;
				}
			}else{
				return false;
			}
		},
		checking: function(callback) {
			$('.maincontainer').hide()
			$.ajax({
				type: "GET",
				url: TUrl + 'supplier/admin/supplier/currentSupplierInfo',
				cache: false, // 禁用缓存
				data: {}, // 传入组装的参数
				dataType: "json",
				headers:{
					authentication: authentication
				},
				success : function(res) {
					if (res.code == 402) {
						location.href = "login.html";
					}else if(res.code == 200){
						if(res.data.reviewStatus == 0){ // 待审核
							layer.open({
								type : 1,
								title : '提示', //标题栏
								closeBtn : 1, //关闭按钮
								area : ['300px','150px'],
								skin : 'layui-layer-molv', //自定义样式
								btn : ['确定'], //按钮
								scrollbar : false, //禁止浏览器滚动条
								btnAlign : 'r', //
								move : true, //禁止拖
								resize : false, //是否允许拉伸
								content : '<p style="text-align:center;margin-top:20px">供应商信息待审核，请联系客服</p>',
								btn1: function(index, layero) {
									layer.close(index)
								},
								cancel : function(index, layero) {
									layer.close(index);
								},
								success: function(layero, index) {
									this.enterConfirm = function(event){
										if(event.keyCode === 13){
											$(".layui-layer-btn0").click();
											return false; //阻止系统默认回车事件
										}
									};
									$(document).on('keydown', this.enterConfirm); //监听键盘事件
							
									// 点击确定按钮回调事件
									$(".layui-layer-btn0").on("click",function() {
										// // console.log("peace and love");
									})
								},
								end: function(){
									$(document).off('keydown', this.enterConfirm); //解除键盘事件
								}
							});
						}else if(res.data.reviewStatus == 2){ // 审核失败
							layer.open({
								type : 1,
								title : '提示', //标题栏
								closeBtn : 1, //关闭按钮
								area : ['300px','150px'],
								skin : 'layui-layer-molv', //自定义样式
								btn : ['确定'], //按钮
								scrollbar : false, //禁止浏览器滚动条
								btnAlign : 'r', //
								move : true, //禁止拖
								resize : false, //是否允许拉伸
								content : '<p style="text-align:center;margin-top:20px">供应商信息审核不通过，请联系客服</p>',
								btn1: function(index, layero) {
									layer.close(index)
								},
								cancel : function(index, layero) {
									layer.close(index);
								},
								success: function(layero, index) {
									this.enterConfirm = function(event){
										if(event.keyCode === 13){
											$(".layui-layer-btn0").click();
											return false; //阻止系统默认回车事件
										}
									};
									$(document).on('keydown', this.enterConfirm); //监听键盘事件
							
									// 点击确定按钮回调事件
									$(".layui-layer-btn0").on("click",function() {
										// // console.log("peace and love");
									})
								},
								end: function(){
									$(document).off('keydown', this.enterConfirm); //解除键盘事件
								}
							});
							
						}else{
							$('.maincontainer').show()
							callback(res.data)
						}
					}else{
						layer.msg(res.msg)
					}
				},
				error : function() {
					layer.msg("请求异常");
					// setTimeout(function () {
					// 	layer.close(load);
					// }, 200);
				},
				complete: function( xhr,data ){
					var authentication = xhr.getResponseHeader('authentication');
					if(authentication){
						localStorage.setItem("xi-can-supplier-authentication", authentication);
					}
				}
			})
		}
	}

	exports('http', http);
});